part of 'index.dart';

enum FriendType { friend, following, followed }

class FriendController extends GetxController {
  FriendController(this.type);
  final FriendType type;
  List<FriendModel> list = [];
  final int _limit = 20;
  int _page = 1;
  bool _noMore = false;

  final refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
    _getList(true);
  }

  void _initData() {
    final result = CacheUtil.get(_key);
    if (result.isNotEmpty) {
      list = (jsonDecode(result) as List)
          .map((e) => FriendModel.fromJson(e))
          .toList();
      update();
    }
  }

  Future<void> _getList([bool refresh = false]) async {
    if (refresh) _page = 1;
    List<FriendModel> result = [];
    switch (type) {
      case FriendType.friend:
        result = await FriendAPI.friendList(pageNum: _page, pageSize: _limit);
        break;
      case FriendType.following:
        result = await FriendAPI.followList(pageNum: _page, pageSize: _limit);
        break;
      case FriendType.followed:
        result = await FriendAPI.fansList(pageNum: _page, pageSize: _limit);
        break;
    }
    if (refresh) list.clear();
    list.addAll(result);
    _page++;
    _noMore = result.length < _limit;
    if (refresh) CacheUtil.set(_key, jsonEncode(list));
    update();
  }

  String get _key {
    return '${Constants.kFriend}_${type}_${UserManager.instance.currentUid}';
  }

  void onRefresh() async {
    try {
      await _getList(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getList();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }
}
